﻿using System;
using System.Globalization;
using System.Windows;
using System.Windows.Markup;
using Brjnk.GpxExplorer.Localization;
using Brjnk.GpxExplorer.UI;
using Brjnk.GpxExplorer.Workspace;

namespace Brjnk.GpxExplorer
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public App()
        {
            instance = this;
        }

        private Brjnk.GpxExplorer.Workspace.Workspace workspace = new Brjnk.GpxExplorer.Workspace.Workspace();

        public Brjnk.GpxExplorer.Workspace.Workspace Workspace { get { return workspace; } }

        private Settings settings;

        public Settings Settings { get { return settings; } }

        private ClipboardWatcher clipboardWatcher;

        public ClipboardWatcher ClipboardWatcher { get { return clipboardWatcher; } }

        public Window RealMainWindow { get; private set; }

        protected override void OnStartup(StartupEventArgs e)
        {
            SpecifyCulture();
#if !DEBUG
            this.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
#endif
            var cacheDirectory = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonApplicationData), "GpxExplorer\\MapCache");
            AppDomain.CurrentDomain.SetData("MapCacheDirectory", cacheDirectory);
            //AppDomain.CurrentDomain.FirstChanceException += new EventHandler<System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs>(CurrentDomain_FirstChanceException);
            settings = new Settings();
            if (settings.UpdateRequired) { settings.Upgrade(); settings.UpdateRequired = false; }
            //settings.Save();

            LoadLocalization();
#if DEBUG && false
            var tool = new LocalizationTool();
            tool.Show();
#endif
            workspace.Initialize();
            RealMainWindow = new MainWindow();
            RealMainWindow.Show();

            base.OnStartup(e);
        }

        /// <summary>
        /// Smaže soubor vyrovnávací paměti, který byl používaný předchozími verzemi.
        /// </summary>
        private void DeleteOldCache()
        {
            string path = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonApplicationData), "MapCache.sdf");
            if (System.IO.File.Exists(path))
            {
                var window = new DeleteOldCacheWindow(path, new System.IO.FileInfo(path).Length);
                if (window.ShowDialog() ?? false)
                {
                    System.IO.File.Delete(path);
                }
            }
        }

        public string GetLocalizationString(string key)
        {
            return Brjnk.GpxExplorer.Localization.LocalizationManager.Instance.GetString(key);
        }

        private void LoadLocalization()
        {
            LocalizationManager.Instance.SetProvider(new XmlLocalizationDataProvider(new Uri("pack://application:,,,/GpxExplorer;component")));
            if (settings.Language.IsValid) LocalizationManager.Instance.Language = (settings.Language);
            else settings.Language = LocalizationManager.Instance.Language;
        }

        private void SpecifyCulture()
        {
            FrameworkElement.LanguageProperty.OverrideMetadata(
        typeof(FrameworkElement),
        new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
        }

        public void MainWindowLoaded()
        {
            clipboardWatcher = new GpxExplorer.Workspace.ClipboardWatcher(RealMainWindow);
            clipboardWatcher.Register();
        }

        public void MainWindowContentRendered()
        {
            workspace.MainWindowContentRendered();
            DeleteOldCache();
        }

        protected override void OnExit(ExitEventArgs e)
        {
            settings.Save();
            Brjnk.Common.UnitsSettings.Instance.Save();
            if (clipboardWatcher != null)
                clipboardWatcher.Unregister();
            ClearTempFiles();
            if (workspace != null)
                workspace.Destroy();
            base.OnExit(e);
        }

        /// <summary>
        /// Odstraní všechny soubory ve složce IO.GetTempPath(), které začínají "GpxExplorerTMP" a jsou starší než x dnů
        /// </summary>
        private void ClearTempFiles()
        {
            foreach (var file in new System.IO.DirectoryInfo(System.IO.Path.GetTempPath()).GetFiles())
            {
                if (file.Name.StartsWith("GpxExplorerTMP", StringComparison.InvariantCultureIgnoreCase) &&
                    file.LastAccessTime.AddDays(10) < DateTime.Now) file.Delete();
            }
        }

        private static App instance;

        public static App Instance { get { return instance; } }

        private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            var window = new ExceptionWindow(e);
            window.Show();
            e.Handled = true;
        }

        private void CurrentDomain_FirstChanceException(object sender, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e)
        {
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {

        }
    }
}